package cn.guetzjb.security.service;

import cn.guetzjb.core.constant.CacheConstants;
import cn.guetzjb.core.constant.SecurityConstants;
import cn.guetzjb.core.utils.JwtUtils;
import cn.guetzjb.redis.service.RedisService;
import cn.guetzjb.security.utils.SecurityUtils;
import cn.guetzjb.sys.domain.SysUser;
import cn.guetzjb.sys.model.LoginUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class TokenService {

    private final Long expireTime = CacheConstants.EXPIRATION;
    private final RedisService redisService;

    public boolean checkUsernamePassword(LoginUser loginUser, String pwd) {
        return SecurityUtils.matchesPassword(pwd, loginUser.getSysUser().getPassword());
    }

    public Map<String, Object> generateToken(LoginUser loginUser) {
        String userKey = UUID.randomUUID().toString();
        String username = loginUser.getUsername();
        Long userId = loginUser.getUserId();
        loginUser.setUserKey(userKey);
        Map<String, Object> claims = Map.of(SecurityConstants.DETAILS_USERNAME, username,
                SecurityConstants.DETAILS_USER_ID, userId, SecurityConstants.USER_KEY, userKey);
        Map<String, Object> res = new HashMap<>();
        res.put("accessToken", "Bearer " + JwtUtils.createToken(claims));
        res.put("expiresIn", expireTime);
        //存入redis
        redisService.setCacheObject(CacheConstants.LOGIN_TOKEN_KEY + userId, loginUser, expireTime, TimeUnit.MINUTES);
        return res;
    }

}
